<?php

namespace rbac\controllers;

use Yii;
use rbac\models\Menu;
use rbac\models\searchs\Menu as MenuSearch;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use rbac\components\Helper;
use backend\classes\Tree;


/**
 * MenuController implements the CRUD actions for Menu model.
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class MenuController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex()
    {





        $tree = new Tree();


        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $data = Menu::find()->orderBy('order ASC,id DESC')->asArray()->all();
		$array = array();
		foreach($data as $r) {
            $r['operation'] = '<a class="layui-btn layui-btn-xs layui-default-view" href="'.Url::to("create?parent=".$r["id"]).'">添加子菜单</a> | <a class="layui-btn layui-btn-normal layui-btn-xs layui-default-update" href="'.Url::to("update?id=".$r["id"]).'">修改</a> | <a href="'.Url::to("delete?id=".$r["id"]).'" class="layui-btn layui-btn-danger layui-btn-xs layui-default-delete">删除</a> ';

            $array[] = $r;
        }
        $str  = "<tr>
					<td align='center'><input name='\$id' type='text' size='3' value='\$order'  class='layui-input listorder' style='width: 50px'></td>

					<td align='center'>\$id</td>
					<td >\$spacer\$name</td>
										<td align='center'>\$operation</td>

				</tr>";
        $tree->init($array);
        $categorys = $tree->get_tree(0, $str);

        return $this->render('index',['categorys'=>$categorys]);
        /*  $searchModel = new MenuSearch;
         $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());


         return $this->render('index', [
                 'dataProvider' => $dataProvider,
                 'searchModel' => $searchModel,
         ]);*/
    }

    /**
     * Displays a single Menu model.
     * @param  integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
                'model' => $this->findModel($id),
        ]);
    }
    public function actionOrder(){
        if (Yii::$app->request->isAjax){
            $str = json_decode(Yii::$app->request->post('str'),1);
            //Menu::updateAll(['order'=>2],['id'=>32]);
            foreach ($str as $k=>$v){
                list($id,$order) = explode('|',$v);
                Menu::updateAll(['order'=>$order],['id'=>$id]);
            }
            Helper::invalidate();
            return json_encode(['code'=>200,"msg"=>"操作成功"]);

        }

    }

    /**
     * Creates a new Menu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($parent='')
    {
        $model = new Menu;
        $model->parent=$parent;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Helper::invalidate();
            return $this->location("index","操作成功");

        } else {
            $tree = new Tree();

            $result = Menu::find()->orderBy('order ASC,id DESC')->asArray()->all();
            $array = array();
            foreach($result as $r) {
                $array[] = $r;
            }
            $str  = "\$id//\$spacer \$name ---";
            $tree->init($array);
            //组成成数组
            $select_categorys = $tree->get_tree(0, $str);

            $arr = array_filter(explode('---',$select_categorys));
            $list=[];
            foreach ($arr as $k=>$v){
                    list($id,$val)=explode('//',$v);
                    $rs['id']=$id;
                    $rs['val']=str_replace('&nbsp;','',$val);
                    $list[]=$rs;
            }
            $model->order=0;
            return $this->render('create', [
                    'model' => $model,
                    'list'=>$list
            ]);
        }
    }

    /**
     * Updates an existing Menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param  integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Helper::invalidate();
            return $this->location("index","操作成功");
        } else {
            $tree = new Tree();

            $result = Menu::find()->orderBy('order ASC,id DESC')->asArray()->all();
            $array = array();
            foreach($result as $r) {
                $array[] = $r;
            }
            $str  = "\$id//\$spacer \$name ---";
            $tree->init($array);
            //组成成数组
            $select_categorys = $tree->get_tree(0, $str);

            $arr = array_filter(explode('---',$select_categorys));
            $list=[];
            foreach ($arr as $k=>$v){
                list($id,$val)=explode('//',$v);
                $rs['id']=$id;
                $rs['val']=str_replace('&nbsp;','',$val);
                $list[]=$rs;
            }

            return $this->render('update', [
                    'model' => $model,
                'list'=>$list

            ]);
        }
    }

    /**
     * Deletes an existing Menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param  integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
		$model = new Menu();

        $condition="id in (".Menu::getChild($id).')';

        $count =Menu::deleteAll($condition);
        if($count>0){
            Helper::invalidate();
            return json_encode(['code'=>200,"msg"=>"删除成功"]);
        }else{
            $errors = $model->firstErrors;
            return json_encode(['code'=>400,"msg"=>reset($errors)]);
        }
    }

    public function actionDeleteAll(){
        $data = Yii::$app->request->post();
        if($data){
            $model = new Menu;
            $count = $model->deleteAll(["in","id",$data['keys']]);
            if($count>0){
				Helper::invalidate();
                return json_encode(['code'=>200,"msg"=>"删除成功"]);
            }else{
				$errors = $model->firstErrors;
                return json_encode(['code'=>400,"msg"=>reset($errors)]);
            }
        }else{
            return json_encode(['code'=>400,"msg"=>"请选择数据"]);
        }
    }
    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param  integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
